<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Search,
  View,
  Share,
  Star,
  ChatDotRound,
  ArrowUp,
  ArrowDown
} from '@element-plus/icons-vue'

// 定义内容项的接口
interface ContentItem {
  id: number;
  content: string;
  time: string;
  source: string;
  author: string;
  topic: string;
  heat_value: number;
  sentiment_value: number;
  keywords?: string[];
}

// 排序变更接口
interface SortChangeParams {
  prop: string;
  order: string;
}

const props = defineProps({
  data: {
    type: Array as () => ContentItem[],
    required: true,
    default: () => []
  },
  type: {
    type: String,
    default: 'all', // 'all', 'positive', 'negative', 'neutral'
    validator: (value: string) => ['all', 'positive', 'negative', 'neutral'].includes(value)
  },
  showDetail: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['view-detail'])

// 搜索功能
const searchQuery = ref('')
const filterType = ref(props.type)

// 分页
const currentPage = ref(1)
const pageSize = ref(10)

// 排序
const sortField = ref('sentiment')
const sortOrder = ref('descending')

// 计算过滤后的数据
const filteredData = computed(() => {
  let result = [...props.data]
  
  // 根据类型过滤
  if (filterType.value !== 'all') {
    result = result.filter(item => {
      if (filterType.value === 'positive') return item.sentiment_value > 0.2
      if (filterType.value === 'negative') return item.sentiment_value < -0.2
      return item.sentiment_value >= -0.2 && item.sentiment_value <= 0.2
    })
  }
  
  // 根据搜索内容过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(item => 
      item.content.toLowerCase().includes(query) || 
      item.source.toLowerCase().includes(query) ||
      item.topic.toLowerCase().includes(query)
    )
  }
  
  // 排序
  result.sort((a: ContentItem, b: ContentItem) => {
    let valA: number | Date, valB: number | Date
    
    switch (sortField.value) {
      case 'time':
        valA = new Date(a.time).getTime()
        valB = new Date(b.time).getTime()
        break
      case 'heat':
        valA = a.heat_value
        valB = b.heat_value
        break
      case 'sentiment':
      default:
        valA = a.sentiment_value
        valB = b.sentiment_value
        break
    }
    
    return sortOrder.value === 'ascending' ? Number(valA) - Number(valB) : Number(valB) - Number(valA)
  })
  
  return result
})

// 计算分页数据
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredData.value.slice(start, end)
})

// 计算总页数
const totalItems = computed(() => filteredData.value.length)

// 获取情感类型类名
const getSentimentClass = (value: number): string => {
  if (value > 0.2) return 'positive'
  if (value < -0.2) return 'negative'
  return 'neutral'
}

// 获取情感强度
const getSentimentIntensity = (value: number): string => {
  const absValue = Math.abs(value)
  if (absValue > 0.7) return '强烈'
  if (absValue > 0.4) return '中等'
  return '轻微'
}

// 处理页面变化
const handlePageChange = (page: number): void => {
  currentPage.value = page
}

// 处理排序变化
const handleSortChange = ({ prop, order }: SortChangeParams): void => {
  if (prop) {
    sortField.value = prop
    sortOrder.value = order
  }
}

// 查看详情
const viewDetail = (item: ContentItem): void => {
  emit('view-detail', item)
}

// 高亮搜索关键词
const highlightText = (text: string): string => {
  if (!searchQuery.value || !text) return text
  
  const query = searchQuery.value
  const regex = new RegExp(query, 'gi')
  return text.replace(regex, (match: string) => `<span class="highlight">${match}</span>`)
}

// 格式化时间
const formatTime = (timeString: string): string => {
  const date = new Date(timeString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 进度条格式化函数
const formatProgress = (percentage: number): string => {
  return `${percentage}`
}

// 生成模拟数据
const mockItems = ref<ContentItem[]>([
  {
    id: 1,
    content: '人工智能技术的最新突破让我们看到了科技的美好未来，这将大大提升我们的工作效率。',
    time: '2023-11-10 10:30:00',
    source: '微博',
    author: '科技爱好者',
    topic: '人工智能',
    heat_value: 89,
    sentiment_value: 0.85,
    keywords: ['人工智能', '科技', '效率']
  },
  {
    id: 2,
    content: '数据安全事件频发，用户隐私保护形势严峻，企业必须加强安全意识。',
    time: '2023-11-10 11:45:00',
    source: '知乎',
    author: '安全专家',
    topic: '数据安全',
    heat_value: 76,
    sentiment_value: -0.65,
    keywords: ['数据安全', '隐私保护', '安全意识']
  },
  {
    id: 3,
    content: '远程办公模式被越来越多的企业采用，工作生活平衡得到改善。',
    time: '2023-11-10 14:20:00',
    source: '今日头条',
    author: '职场观察',
    topic: '远程办公',
    heat_value: 82,
    sentiment_value: 0.72,
    keywords: ['远程办公', '工作生活平衡', '企业']
  },
  {
    id: 4,
    content: '元宇宙概念股今日大幅波动，投资者需谨慎对待市场炒作行为。',
    time: '2023-11-10 15:30:00',
    source: '财经网',
    author: '投资分析师',
    topic: '元宇宙',
    heat_value: 68,
    sentiment_value: -0.15,
    keywords: ['元宇宙', '概念股', '投资']
  },
  {
    id: 5,
    content: '芯片短缺问题仍未得到有效解决，多家企业生产受到影响，供应链风险上升。',
    time: '2023-11-11 09:15:00',
    source: '新浪财经',
    author: '产业观察家',
    topic: '芯片短缺',
    heat_value: 92,
    sentiment_value: -0.78,
    keywords: ['芯片短缺', '供应链', '风险']
  }
])

// 合并props数据和模拟数据
const combinedData = computed((): ContentItem[] => {
  // 如果props.data非空，则使用props.data，否则使用模拟数据
  return props.data.length > 0 ? props.data : mockItems.value
})

onMounted(() => {
  // 初始化时，设置过滤类型
  filterType.value = props.type
})
</script>

<template>
  <div class="sentiment-content-analysis">
    <!-- 搜索和过滤工具栏 -->
    <div class="toolbar">
      <div class="search-box">
        <el-input
          v-model="searchQuery"
          placeholder="搜索内容、来源或话题"
          prefix-icon="el-icon-search"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      
      <div class="filter-box">
        <el-radio-group v-model="filterType" size="small">
          <el-radio-button label="all">全部</el-radio-button>
          <el-radio-button label="positive">正面</el-radio-button>
          <el-radio-button label="neutral">中性</el-radio-button>
          <el-radio-button label="negative">负面</el-radio-button>
        </el-radio-group>
      </div>
    </div>
    
    <!-- 数据表格 -->
    <el-table
      :data="paginatedData"
      style="width: 100%"
      @sort-change="handleSortChange"
      :default-sort="{ prop: sortField, order: sortOrder }"
    >
      <el-table-column prop="time" label="时间" sortable="custom" width="160">
        <template #default="scope">
          {{ formatTime(scope.row.time) }}
        </template>
      </el-table-column>
      
      <el-table-column prop="content" label="内容">
        <template #default="scope">
          <div class="content-cell">
            <div class="content-text" v-html="highlightText(scope.row.content)"></div>
            <div class="content-meta">
              <span class="source">
                <el-tag size="small">{{ scope.row.source }}</el-tag>
              </span>
              <span class="topic">
                <el-tag type="info" size="small">{{ scope.row.topic }}</el-tag>
              </span>
              <span class="keywords" v-if="scope.row.keywords">
                <el-tag 
                  v-for="(keyword, index) in scope.row.keywords" 
                  :key="index"
                  type="success"
                  effect="plain"
                  size="small"
                >
                  {{ keyword }}
                </el-tag>
              </span>
            </div>
          </div>
        </template>
      </el-table-column>
      
      <el-table-column prop="heat_value" label="热度" sortable="custom" width="100">
        <template #default="scope">
          <el-progress 
            :percentage="scope.row.heat_value" 
            :color="scope.row.heat_value > 80 ? '#F56C6C' : scope.row.heat_value > 60 ? '#E6A23C' : '#409EFF'"
            :format="formatProgress"
          />
        </template>
      </el-table-column>
      
      <el-table-column prop="sentiment_value" label="情感值" sortable="custom" width="120">
        <template #default="scope">
          <div :class="['sentiment-value', getSentimentClass(scope.row.sentiment_value)]">
            <el-icon v-if="scope.row.sentiment_value > 0.2"><ArrowUp /></el-icon>
            <el-icon v-else-if="scope.row.sentiment_value < -0.2"><ArrowDown /></el-icon>
            {{ scope.row.sentiment_value.toFixed(2) }}
            <span class="intensity">{{ getSentimentIntensity(scope.row.sentiment_value) }}</span>
          </div>
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="120" v-if="showDetail">
        <template #default="scope">
          <div class="action-buttons">
            <el-button type="primary" :icon="View" size="small" circle @click="viewDetail(scope.row)" />
            <el-button type="success" :icon="Share" size="small" circle />
          </div>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页器 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="totalItems"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<style scoped>
.sentiment-content-analysis {
  width: 100%;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-box {
  width: 300px;
}

.content-cell {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.content-text {
  font-size: 14px;
  line-height: 1.5;
}

.content-meta {
  display: flex;
  gap: 8px;
  align-items: center;
  flex-wrap: wrap;
}

.keywords {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

.sentiment-value {
  display: flex;
  align-items: center;
  gap: 5px;
  font-weight: 500;
}

.sentiment-value.positive {
  color: #67C23A;
}

.sentiment-value.negative {
  color: #F56C6C;
}

.sentiment-value.neutral {
  color: #909399;
}

.intensity {
  font-size: 12px;
  opacity: 0.8;
  margin-left: 5px;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.highlight) {
  background-color: #FFFB8F;
  padding: 0 2px;
  border-radius: 2px;
}
</style> 